﻿#include "SafeStack.h"
#include <algorithm>

// 构造函数
template<typename T>
SafeStack<T>::SafeStack(size_t cap) : capacity(cap) {}

// 入栈
template<typename T>
void SafeStack<T>::push(const T& value) {
    std::lock_guard<std::mutex> lock(mtx);
    if (dataStack.size() >= capacity)
        throw std::overflow_error("Stack capacity exceeded");

    dataStack.push(value);

    if (minStack.empty())
        minStack.push(value);
    else
        minStack.push(std::min(value, minStack.top()));

    if (maxStack.empty())
        maxStack.push(value);
    else
        maxStack.push(std::max(value, maxStack.top()));
}

// 出栈
template<typename T>
void SafeStack<T>::pop() {
    std::lock_guard<std::mutex> lock(mtx);
    if (dataStack.empty())
        throw std::underflow_error("Stack is empty");

    dataStack.pop();
    minStack.pop();
    maxStack.pop();
}

// 栈顶
template<typename T>
T SafeStack<T>::top() const {
    std::lock_guard<std::mutex> lock(mtx);
    if (dataStack.empty())
        throw std::underflow_error("Stack is empty");
    return dataStack.top();
}

// 最小值
template<typename T>
T SafeStack<T>::min() const {
    std::lock_guard<std::mutex> lock(mtx);
    if (minStack.empty())
        throw std::underflow_error("Stack is empty");
    return minStack.top();
}

// 最大值
template<typename T>
T SafeStack<T>::max() const {
    std::lock_guard<std::mutex> lock(mtx);
    if (maxStack.empty())
        throw std::underflow_error("Stack is empty");
    return maxStack.top();
}

// 是否为空
template<typename T>
bool SafeStack<T>::empty() const {
    std::lock_guard<std::mutex> lock(mtx);
    return dataStack.empty();
}

// 栈大小
template<typename T>
size_t SafeStack<T>::size() const {
    std::lock_guard<std::mutex> lock(mtx);
    return dataStack.size();
}

// 清空
template<typename T>
void SafeStack<T>::clear() {
    std::lock_guard<std::mutex> lock(mtx);
    while (!dataStack.empty()) {
        dataStack.pop();
        minStack.pop();
        maxStack.pop();
    }
}

// 显示实例化常用类型
template class SafeStack<int>;
template class SafeStack<double>;
template class SafeStack<float>;
template class SafeStack<long>;
template class SafeStack<std::string>;
